/**
 * 功能：初始化数据
 * @param {Object} paramObjName：初始化参数对象的实例名
 * @param {Object} updateUrl: 更新读取记录的URL地址
 * @param {Object} deleteUrl: 删除数据对应的URL地址
 * @param {Object} tableId：列表数据表格的ID
 * @param {Object} searchID：查询对应的id
 * @param {Object} resetSearchID：查询重置的id
 * @param {Object} searchFormID:普通查找对应的form的ID
 * @param {Object} addDataFormId:添加数据对应Form的ID
 * @param {Object} addDialogWidth:添加数据对应对话框的宽度
 * @param {Object} addDialogHeight:添加数据对应对话框的高度
 * @param {Object} ctx:页面对应的上下文
 * @param {Object} addDialogTitle:添加数据对应对话框的标题
 */
function initParams(initData) {
    this.paramObjName = initData.paramObjName;
    this.updateUrl = initData.updateUrl;
    this.deleteUrl = initData.deleteUrl;
    this.addDataFormId = initData.addDataFormId || 'addDataForm';
    this.searchID = initData.searchID || 'search';
    this.resetSearchID = initData.resetSearchID || 'resetSearch';
    this.searchFormID = initData.searchFormID || 'searchForm';
    this.tableId = initData.tableId || 'listTable';
    this.addDialogWidth = initData.addDialogWidth;
    this.addDialogHeight = initData.addDialogHeight;
    this.ctx = initData.ctx;
    this.addDialogTitle = initData.addDialogTitle;
    this.saveButton = initData.saveButton || i18n.saveButton;
    this.cancelButton = initData.cancelButton || i18n.cancelButton;
    this.showDialogId = initData.showDialogId || 'showDialog';
}

/**
 * 功能：初始化数据
 * @param {Object} paramObjName：初始化参数对象的实例名
 * @param {Object} updateUrl: 更新读取记录的URL地址
 * @param {Object} deleteUrl: 删除数据对应的URL地址
 * @param {Object} tableId：列表数据表格的ID
 * @param {Object} searchID：查询对应的id
 * @param {Object} resetSearchID：查询重置的id
 * @param {Object} searchFormID:普通查找对应的form的ID
 * @param {Object} addDataFormId:添加数据对应Form的ID
 * @param {Object} addDialogWidth:添加数据对应对话框的宽度
 * @param {Object} addDialogHeight:添加数据对应对话框的高度
 * @param {Object} ctx:页面对应的上下文
 * @param {Object} addDialogTitle:添加数据对应对话框的标题
 * @param {Object} auctionInfoDialogId:竞拍页面
 */
function initAuctionParams(initData) {
    this.paramObjName = initData.paramObjName;
    this.updateUrl = initData.updateUrl;
    this.deleteUrl = initData.deleteUrl;
    this.addDataFormId = initData.addDataFormId || 'addDataForm';
    this.searchID = initData.searchID || 'search';
    this.resetSearchID = initData.resetSearchID || 'resetSearch';
    this.searchFormID = initData.searchFormID || 'searchForm';
    this.tableId = initData.tableId || 'listTable';
    this.addDialogWidth = initData.addDialogWidth;
    this.addDialogHeight = initData.addDialogHeight;
    this.ctx = initData.ctx;
    this.addDialogTitle = initData.addDialogTitle;
    this.saveButton = initData.saveButton || i18n.saveButton;
    this.cancelButton = initData.cancelButton || i18n.cancelButton;
    this.showDialogId = initData.showDialogId || 'showDialog';
    this.auctionInfoDialogId = initData.auctionInfoDialogId || 'auctionInfoDialog';
}


/**
 * 初始化查询
 * @param {Object} paramObj ： 初始化参数对象的实例名
 */
function init(paramObj) {
    $('#' + paramObj.searchFormID).show();
    //普通查询
    $("#" + paramObj.searchID).click(function () {
        //$("#"+paramObj.searchID).attr('disabled',true);
        queryData(paramObj);
    });
    //普通查询清空操作
    $("#" + paramObj.resetSearchID).click(function () {
        $("#" + paramObj.searchFormID).find(".easyui-combobox").each(function () {
            $(this).combobox('setValue', "");
        });
        $("#" + paramObj.searchFormID).find("input").each(function () {
            $(this).val("");
        });
        $("#" + paramObj.searchFormID).find(".easyui-datebox").each(function () {
            $(this).datebox("setValue", "");
        });
        $("#" + paramObj.searchFormID).find(".easyui-datetimebox").each(function () {
            $(this).datebox("setValue", "");
        });
//		$("#"+paramObj.searchFormID+" input:visible").val("");
//		$("#"+paramObj.searchFormID).find("select").each(function(){
//			var value = $(this).combobox('getData')[0].value;
//			$(this).combobox('select',value);
//		});
    });
}

function queryData(paramObj) {
    if ($('#' + paramObj.searchFormID).form('validate')) {
        var queryParam = $("#" + paramObj.searchFormID).serialize();
        queryParam = decodeURIComponent(queryParam.replace(/\+/g, " "), true);
        var queryParams = {};
        if (queryParam != undefined) {
            var queryParamSplit = queryParam.split("&");
            for (var i = 0; i < queryParamSplit.length; i++) {
                var queryNameValue = queryParamSplit[i].split('=');
                queryParams[queryNameValue[0]] = queryNameValue[1];
            }
        }
        $('#' + paramObj.tableId).datagrid('options').queryParams = queryParams;
        $('#' + paramObj.tableId).datagrid('load');
    }
}

/**
 * 打开添加数据的页面的对话框
 * @param {Object} paramObj ： 对应的列表对象
 * @param {Object} id ： 数据记录的ID
 * @param {Object} successcallback ：添加数据成功后的回调函数
 * @param {Object} failurecallback ： 添加数据失败后的回调函数
 */
function openDataDialog(paramObj, id, successcallback, failurecallback) {
    if (id == undefined) {
        id = '';
    }
    var sign = false;
    top.$('#' + paramObj.showDialogId).dialog({
        title: paramObj.addDialogTitle,
        iconCls: 'icon-view',
        width: paramObj.addDialogWidth,
        height: paramObj.addDialogHeight,
        closed: false,
        inline: true,
        cache: false,
        href: paramObj.updateUrl + id,
        modal: true,
        extractor: function (data) {
            if ($.trim(data) == "unLogin") {
                var msn = '' || i18n[''];
                msn = msn || i18n[data];
                if (msn != undefined) {
                    $.messager.alert('提示', msn, 'info', function () {
                        top.location = paramObj.ctx + '/manage';
                    });
                    return '';
                }
            }
            return data;
        },
        buttons: [{
            text: paramObj.saveButton,
            id: 'saveEntityBt',
            iconCls: 'icon-ok',
            handler: function () {
                saveEntity(paramObj, 'saveEntityBt', successcallback, failurecallback);
            }
        }, {
            text: paramObj.cancelButton,
            iconCls: 'icon-cancel',
            handler: function () {
                top.$('#' + paramObj.showDialogId).dialog('close');
            }
        }]
    });
    top.$('#' + paramObj.showDialogId).dialog("center");
}

/**
 * 添加、更新保存数据
 * @param {Object} paramObj:表格对应的初始化对象
 * @param {Object} opBtId: 代表保存数据按钮对应的ID，进行防止重复提交的作用
 * @param {Object} successcallback：在调用添加成功后调用的初始化回调方法
 * @param {Object} failurecallback：在调用添加失败后调用的初始化回调方法
 */
function saveEntity(paramObj, opBtId, successcallback, failurecallback) {
    if (top.$('#' + paramObj.addDataFormId).form('validate')) {
        top.$('#' + opBtId).linkbutton('disable');
        $.ajax({
            type: "POST",
            timeout: 20000,
            url: top.$('#' + paramObj.addDataFormId).attr("action"),
            data: top.$("#" + paramObj.addDataFormId).serialize(),
            success: function (data, res) {
                var msn = '' || i18n[''];
                var result = $.trim(res.responseText);
                if (result == "unLogin") {
                    msn = msn || i18n[result];
                    if (msn != undefined) {
                        top.$.messager.alert('提示', msn, 'info', function () {
                            top.location = paramObj.ctx + '/manage';
                        });
                        return;
                    }
                }
                msn = msn || i18n[data];
                if (msn == undefined) {
                    top.$.messager.alert('提示', i18n.serverError, 'info');
                } else if (msn) {
                    top.$.messager.alert('提示', msn, 'info', function () {
                        $('#' + paramObj.tableId).datagrid('reload');
                        top.$('#' + paramObj.showDialogId).dialog('close');
                    });
                }
                if (successcallback != undefined) {
                    successcallback();
                }
            },
            error: function (res) {
                top.$.messager.alert('提示', i18n.requestError, 'error');
                top.$('#' + opBtId).linkbutton('enable');
                if (failurecallback != undefined) {
                    failurecallback();
                }
            }
        });
    }
}

/**
 * 选择记录更新数据
 * @param {Object} paramObj:表格对应的初始化对象
 * @param {Object} successcallback：在调用更新成功后调用的初始化回调方法
 * @param {Object} failurecallback：在调用更新失败后调用的初始化回调方法
 */
function updateData(paramObj, successcallback, failurecallback) {
    var records = $('#' + paramObj.tableId).datagrid('getSelections');
    if (records.length != 1) {
        $.messager.alert('提示', "请选择一条记录！", 'info');
    } else {
        var record = records[0];
        openDataDialog(paramObj, record.id, successcallback, failurecallback);
    }
}

/**
 * 根据选择的记录进行删除数据
 * @param {Object} paramObj ： 表格对应的初始化对象
 * @param {Object} successcallback：在调用删除成功后调用的初始化回调方法
 * @param {Object} failurecallback：在调用删除失败后调用的初始化回调方法
 */
function deleteData(paramObj, successcallback, failurecallback) {
    var records = $('#' + paramObj.tableId).datagrid('getSelections');
    if (records.length < 1) {
        $.messager.alert('提示', "请选择记录！", 'info');
    } else {
        var deleteIds = '';
        for (var i = 0; i < records.length - 1; i++) {
            deleteIds += records[i].id + ",";
        }
        deleteIds += records[records.length - 1].id;
        top.$.messager.confirm('提示', "确定删除这条记录吗？", function (result) {
            if (result) {
                var msn = '' || i18n[''];
                $.ajax({
                    type: "get",
                    url: paramObj.deleteUrl,
                    data: 'deleteIds=' + deleteIds,
                    success: function (data, res) {
                        var msn = '' || i18n[''];
                        var result = $.trim(res.responseText);
                        if (result == "unLogin") {
                            msn = msn || i18n[result];
                            if (msn != undefined) {
                                $.messager.alert('提示', msn, 'info', function () {
                                    top.location = paramObj.ctx + '/manage';
                                });
                                return;
                            }
                        }
                        msn = msn || i18n[data];
                        if (msn == undefined) {
                            $.messager.alert('提示', i18n.serverError, 'error');
                        } else if (msn) {
                            // TODO 使用动态提醒
                            //animateShowMsg('ok', msn);
                            if (successcallback != undefined) {
                                successcallback();
                            }
                            $.messager.alert('提示', msn, 'info', function () {
                                $('#' + paramObj.tableId).datagrid('reload');
                            });
                        }
                    },
                    error: function (res) {
                        $.messager.alert('提示', i18n.requestError, 'error');
                        if (failurecallback != undefined) {
                            failurecallback();
                        }
                    }
                });
            }
        });
    }
}

/**
 * by 冯亚
 * 检测指定容器还可以输入多少个字
 * tipId:提示框Id
 * countNum:共可以输入的字数
 * id:输入框（文本域Id）
 */
function checkLength(tipId, countNum, id) {
    var curLength = document.getElementById(id).value.length;
    if (curLength > countNum) {
        document.getElementById(id).value = document.getElementById(id).value.substr(0, countNum);
        // 解决回车双字符的问题
        if (document.getElementById(id).value.length > countNum) {
            document.getElementById(id).value = document.getElementById(id).value.substr(0, countNum - 1);
            curLength = countNum;
        }
        curLength = countNum;
    }
    document.getElementById(tipId).innerHTML = countNum - document.getElementById(id).value.length;
}

/**
 * 装换大写数字
 * @param currencyDigits
 * @returns
 */
function convertCurrency(currencyDigits) {
    // Constants:
    var MAXIMUM_NUMBER = 99999999999.99;
    // Predefine the radix characters and currency symbols for output:
    var CN_ZERO = "零";
    var CN_ONE = "壹";
    var CN_TWO = "贰";
    var CN_THREE = "叁";
    var CN_FOUR = "肆";
    var CN_FIVE = "伍";
    var CN_SIX = "陆";
    var CN_SEVEN = "柒";
    var CN_EIGHT = "捌";
    var CN_NINE = "玖";
    var CN_TEN = "拾";
    var CN_HUNDRED = "佰";
    var CN_THOUSAND = "仟";
    var CN_TEN_THOUSAND = "万";
    var CN_HUNDRED_MILLION = "亿";
    var CN_DOLLAR = "元";
    var CN_TEN_CENT = "角";
    var CN_CENT = "分";
    var CN_INTEGER = "整";

    // Variables:
    var integral; // Represent integral part of digit number.
    var decimal; // Represent decimal part of digit number.
    var outputCharacters; // The output result.
    var parts;
    var digits, radices, bigRadices, decimals;
    var zeroCount;
    var i, p, d;
    var quotient, modulus;

    // Validate input string:
    currencyDigits = currencyDigits.toString();
    if (currencyDigits == "") {
        //alert("Empty input!");
        return "";
    }
    if (currencyDigits.match(/[^,.\d]/) != null) {
        //alert("Invalid characters in the input string!");
        return "";
    }
    if ((currencyDigits).match(/^((\d{1,3}(,\d{3})*(.((\d{3},)*\d{1,3}))?)|(\d+(.\d+)?))$/) == null) {
        // alert("Illegal format of digit number!");
        return "";
    }

    // Normalize the format of input digits:
    currencyDigits = currencyDigits.replace(/,/g, ""); // Remove comma delimiters.
    currencyDigits = currencyDigits.replace(/^0+/, ""); // Trim zeros at the beginning.
    // Assert the number is not greater than the maximum number.
    if (Number(currencyDigits) > MAXIMUM_NUMBER) {
        //alert("Too large a number to convert!");
        return "";
    }

    // Process the coversion from currency digits to characters:
    // Separate integral and decimal parts before processing coversion:
    parts = currencyDigits.split(".");
    if (parts.length > 1) {
        integral = parts[0];
        decimal = parts[1];
        // Cut down redundant decimal digits that are after the second.
        decimal = decimal.substr(0, 2);
    } else {
        integral = parts[0];
        decimal = "";
    }
    // Prepare the characters corresponding to the digits:
    digits = new Array(CN_ZERO, CN_ONE, CN_TWO, CN_THREE, CN_FOUR, CN_FIVE, CN_SIX, CN_SEVEN, CN_EIGHT, CN_NINE);
    radices = new Array("", CN_TEN, CN_HUNDRED, CN_THOUSAND);
    bigRadices = new Array("", CN_TEN_THOUSAND, CN_HUNDRED_MILLION);
    decimals = new Array(CN_TEN_CENT, CN_CENT);
    // Start processing:
    outputCharacters = "";
    // Process integral part if it is larger than 0:
    if (Number(integral) > 0) {
        zeroCount = 0;
        for (i = 0; i < integral.length; i++) {
            p = integral.length - i - 1;
            d = integral.substr(i, 1);
            quotient = p / 4;
            modulus = p % 4;
            if (d == "0") {
                zeroCount++;
            } else {
                if (zeroCount > 0) {
                    outputCharacters += digits[0];
                }
                zeroCount = 0;
                outputCharacters += digits[Number(d)] + radices[modulus];
            }
            if (modulus == 0 && zeroCount < 4) {
                outputCharacters += bigRadices[quotient];
            }
        }
        outputCharacters += CN_DOLLAR;
    }
    // Process decimal part if there is:
    if (decimal != "") {
        for (i = 0; i < decimal.length; i++) {
            d = decimal.substr(i, 1);
            if (d != "0") {
                outputCharacters += digits[Number(d)] + decimals[i];
            }
        }
    }
    // Confirm and return the final output string:
    if (outputCharacters == "") {
        outputCharacters = CN_ZERO + CN_DOLLAR;
    }
    if (decimal == "") {
        outputCharacters += CN_INTEGER;
    }
    outputCharacters = outputCharacters;
    return outputCharacters;
}

/**
 * easyui combobox 开启搜索功能,自动装载选中的项目处理函数
 */
function onComboboxHidePanel() {
    var el = $(this);
    el.combobox('textbox').focus();
    // 检查录入内容是否在数据里
    var opts = el.combobox("options");
    var data = el.combobox("getData");
    var value = el.combobox("getValue");
    // 有高亮选中的项目, 则不进一步处理
    var panel = el.combobox("panel");
    var items = panel.find(".combobox-item-selected");
    if (items.length > 0) {
        var values = el.combobox("getValues");
        el.combobox("setValues", values);
        return;
    }
    var allowInput = opts.allowInput;
    if (allowInput) {
        var idx = data.length;

        data[idx] = [];
        data[idx][opts.textField] = value;
        data[idx][opts.valueField] = value;
        el.combobox("loadData", data);
    } else {
        // 不允许录入任意项, 则清空
        el.combobox("clear");
    }
}

/**
 *打开文件 方式选择
 */
function showOpenFile(ctx, id, urlStr) {
    //debugger;
    top.$('#threeLevelDialog').dialog({
        title: "打开文件方式",
        iconCls: 'icon-view',
        width: 250,
        height: 90,
        closed: false,
        inline: true,
        cache: false,
        //  href: "${ctx}/business/projectmanage/getBidDetail?id=" + id,
        modal: true,
        extractor: function (data) {
            if ($.trim(data) == "unLogin") {
                var msn = '' || i18n[''];
                msn = msn || i18n[data];
                if (msn != undefined) {
                    top.$.messager.alert('提示', msn, 'info', function () {
                        top.location = '../manage';
                    });
                    return '';
                }
            }
            return data;
        },
        buttons: [{
            text: '下载',
            iconCls: 'icon-download',
            handler: function () {
                $('#threeLevelDialog').dialog('close');
                window.open("../office/plugin/down?resId=" + id);
            }
        },
            {
                text: '直接打开',
                iconCls: 'icon-search',
                handler: function () {
                    var _url = escape(urlStr ? urlStr : "");
                    $('#threeLevelDialog').dialog('close');
                    window.open(ctx + "/office/plugin/open?urlStr=" + _url + "&resId=" + id, "_blank");

                }
            },
            {
                text: '取消',
                iconCls: 'icon-cancel',
                handler: function () {
                    $('#threeLevelDialog').dialog('close');
                }
            }]
    });
    top.$('#threeLevelDialog').dialog("center");

}

/*
 * 响应文件(竞价内容)校验
 */
function noEdit(ti) {
    debugger;
    var val = $(".noEdit").val();//$(ti).text();
    if (val.length != 0 && val.length != 47) {
        top.$.messager.alert('提示', "此项内容只可删除不可编辑！", 'error');
    }
}


//加载数据loading-info
function loadinginfo() {
    top.$('#secondtLevelDialog').dialog({
        closable: false,
        title: '数据加载',
        width: '300',
        height: '200',
        closed: false,
        inline: true,
        cache: false,
        href: "../commons/js/loading/loading-info.html",
        modal: true,
        buttons: [],
        extractor: function (data) {
            if ($.trim(data) == "unLogin") {
                var msn = '' || i18n[''];
                msn = msn || i18n[data];
                if (msn != undefined) {
                    top.$.messager.alert('提示', msn, 'info', function () {
                        top.location = '../../user-login-sys-new/loginPwd';
                    });
                    return '';
                }
            }
            return data;
        }
    });
    top.$('#secondtLevelDialog').dialog("center");
}


/**
 * 获取浏览器宽度和高度
 * @return
 */
var winWidth = 0;
var winHeight = 0;

function getWinWH() {

    //获取窗口宽度
    if (window.innerWidth)
        winWidth = window.innerWidth;
    else if ((document.body) && (document.body.clientWidth))
        winWidth = document.body.clientWidth;
    // 获取窗口高度
    if (window.innerHeight)
        winHeight = window.innerHeight;
    else if ((document.body) && (document.body.clientHeight))
        winHeight = document.body.clientHeight;
    // 通过深入 Document 内部对 body 进行检测，获取窗口大小
    if (document.documentElement && document.documentElement.clientHeight
        && document.documentElement.clientWidth) {
        winHeight = document.documentElement.clientHeight;
        winWidth = document.documentElement.clientWidth;
    }
}


/**
 * 获取当前时间
 */
function myformatter(date) {
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    var d = date.getDate();
    return y + '-' + (m < 10 ? ('0' + m) : m) + '-' + (d < 10 ? ('0' + d) : d);
}

/**
 *格式化当前时间
 */
function myparser(s) {
    if (!s)
        return new Date();
    var ss = (s.split('-'));
    var y = parseInt(ss[0], 10);
    var m = parseInt(ss[1], 10);
    var d = parseInt(ss[2], 10);
    if (!isNaN(y) && !isNaN(m) && !isNaN(d)) {
        return new Date(y, m - 1, d);
    } else {
        return new Date();
    }
}


/**
 * 检查是否安装flash
 * @returns {{f: number, v: number}}
 */
function flashChecker() {
    var hasFlash = 0;         //是否安装了flash
    var flashVersion = 0; //flash版本
    var isIE = /*@cc_on!@*/0;      //是否IE浏览器

    if (isIE) {
        var swf = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
        if (swf) {
            hasFlash = 1;
            VSwf = swf.GetVariable("$version");
            flashVersion = parseInt(VSwf.split(" ")[1].split(",")[0]);
        }
    } else {
        if (navigator.plugins && navigator.plugins.length > 0) {
            var swf = navigator.plugins["Shockwave Flash"];
            if (swf) {
                hasFlash = 1;
                var words = swf.description.split(" ");
                for (var i = 0; i < words.length; ++i) {
                    if (isNaN(parseInt(words[i]))) continue;
                    flashVersion = parseInt(words[i]);
                }
            }
        }
    }
    return {f: hasFlash, v: flashVersion};
}

/*** 对Date的扩展，将 Date 转化为指定格式的String * 月(M)、日(d)、12小时(h)、24小时(H)、分(m)、秒(s)、周(E)、季度(q)
 可以用 1-2 个占位符 * 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字) * eg: * (new
 Date()).pattern("yyyy-MM-dd hh:mm:ss.S")==> 2006-07-02 08:09:04.423
 * (new Date()).pattern("yyyy-MM-dd E HH:mm:ss") ==> 2009-03-10 二 20:09:04
 * (new Date()).pattern("yyyy-MM-dd EE hh:mm:ss") ==> 2009-03-10 周二 08:09:04
 * (new Date()).pattern("yyyy-MM-dd EEE hh:mm:ss") ==> 2009-03-10 星期二 08:09:04
 * (new Date()).pattern("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
 */
Date.prototype.pattern = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, //小时
        "H+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    var week = {
        "0": "/u65e5",
        "1": "/u4e00",
        "2": "/u4e8c",
        "3": "/u4e09",
        "4": "/u56db",
        "5": "/u4e94",
        "6": "/u516d"
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    if (/(E+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "/u661f/u671f" : "/u5468") : "") + week[this.getDay() + ""]);
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
}

